#!/bin/zsh

if [[ -z "${VCPKG_ROOT}" ]]; then
    echo "Error: VCPKG_ROOT environment variable is not set."
    echo "Please set it to your vcpkg installation directory, e.g.:"
    echo 'export VCPKG_ROOT="$HOME/vcpkg"'
    exit 1
fi

mkdir -p out/xcode_ios
cd out/xcode_ios

VCPKG_TOOLCHAIN="${VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake"

if [[ ! -f "${VCPKG_TOOLCHAIN}" ]]; then
    echo "Error: iOS toolchain file not found at ${VCPKG_TOOLCHAIN}."
    echo "Make sure vcpkg is installed and supports iOS."
    exit 1
fi

# Determine target platform
TARGET=${1:-"device"}  # Default to device if no argument provided
ARCH="arm64"
TRIPLET="arm64-ios"
SDKROOT="iphoneos"
PLATFORM_NAME="iphoneos"

if [[ "$TARGET" == "simulator" ]]; then
    # For Apple Silicon simulators (M1/M2)
    TRIPLET="arm64-ios-simulator"
    SDKROOT="iphonesimulator"
    PLATFORM_NAME="iphonesimulator"
    
    # Uncomment below for Intel simulators
    # TRIPLET="x64-ios-simulator"
    # ARCH="x86_64"
fi

# Run CMake configuration (Xcode + iOS)
cmake ../.. -G Xcode \
    -DCMAKE_SYSTEM_NAME=iOS \
    -DCMAKE_OSX_ARCHITECTURES="$ARCH" \
    -DCMAKE_OSX_DEPLOYMENT_TARGET=18.5 \
    -DCMAKE_XCODE_GENERATE_SCHEME=TRUE \
    -DCMAKE_XCODE_SCHEME_ENABLE_GPU_API_VALIDATION=FALSE \
    -DCMAKE_XCODE_SCHEME_ENABLE_GPU_FRAME_CAPTURE_MODE=DISABLED \
    -DCMAKE_FIND_ROOT_PATH_MODE_LIBRARY=BOTH \
    -DCMAKE_FIND_ROOT_PATH_MODE_INCLUDE=BOTH \
    -DCMAKE_TOOLCHAIN_FILE="${VCPKG_TOOLCHAIN}" \
    -DCMAKE_MACOSX_BUNDLE=TRUE \
    -DVCPKG_TARGET_TRIPLET="$TRIPLET"

echo "Xcode project for iOS ($TARGET) generated in: ${PWD}"